package cn.itcast.cargo;

import cn.itcast.domain.vo.ContractProductVo;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/contract")
public class OutProductController extends BaseController {
    @Reference
    private ContractService contractService;
    /**
     * 请求路径/cargo/contract/print.do
     * 响应路径："cargo/print/contract-print";
     */
    //点击进入页面
    @RequestMapping("print")
    public String print(){
        return "cargo/print/contract-print";
    }

    /**
     *  请求路径：/cargo/contract/printExcel.do
     *  请求参数：inputDate
     *  响应路径："cargo/print/contract-print";
     */
    //模板
    @RequestMapping("printExcel")
    public void  printExcel(String inputDate) throws IOException {
        //模板1.加载配置文件流
        InputStream in = session.getServletContext().getResourceAsStream("/make/xlsprint/tOUTPRODUCT.xlsx");
        //一.导出第一行
        //创建工作薄（07版本的）
        Workbook workbook = new XSSFWorkbook(in);
        //2.获取工作表
        Sheet sheet = workbook.getSheetAt(0);
      //获取第一行第二列
        Row row = sheet.getRow(0);
        Cell cell = row.getCell(1);

        String bigTitle = inputDate.replace("-0","-").replace("-","年")+ "月份出货表";

        //设置单元格内容
        cell.setCellValue(bigTitle);


        //二：获取第三行样式
        CellStyle[] cellStyles = new CellStyle[8];
        //获取第三行
         row = sheet.getRow(2);
        for (int i = 0; i < cellStyles.length; i++) {
            //获取第三行的每一列，设置到数组中
            cellStyles[i]= row.getCell(i + 1).getCellStyle();
        }

        //三：导出数据行（调用service查询）
          //参数1：根据日期查询，dao映射语句：and c.ship_time Like'2019-07%'
        List<ContractProductVo> list = contractService.findByShipTime(inputDate + "%", getLoginCompanyId());
        if (list!=null && list.size()>0){
            int index=2;
            Object [] obj=null;
            for (ContractProductVo cp : list) {
                //创建第三行从第三行开始
                row = sheet.createRow(index++);

                //定义一个object[]存储每一行数据
               obj= new Object[]{
                       cp.getCustomName(),
                       cp.getContractNo(),
                       cp.getProductNo(),
                       cp.getCnumber(),
                       cp.getFactoryName(),
                       cp.getDeliveryPeriod(),
                       cp.getShipTime(),
                       cp.getTradeTerms()
               };
               //创建当前行的每一列
                for (int i = 0; i < obj.length; i++) {
                    cell = row.createCell(i + 1);
                    if (!(obj[i] instanceof Date)){
                        cell.setCellValue(obj[i].toString());
                    }else {
                        //处理日期类型，把date日期转为字符串
                        cell.setCellValue(parseDate((Date) obj[i]));
                    }
                    cell.setCellStyle(cellStyles[i]);
                }
            }
        }
        //四：导出下载
        //1.设置响应头（http协议的固定下载格式）
        response.setHeader("content-disposition","attachment;fileName=export.xlsx");
        //获取response输出流
        ServletOutputStream out = response.getOutputStream();
        //把excel文件写入到response输出流，实现下载
        workbook.write(out);
        //关流
        workbook.close();
        out.close();
    }


    // 日期转换为字符串
    private String parseDate(Date date){
        if (date != null) {
            return new SimpleDateFormat("yyyy-MM-dd").format(date);
        }
        // 导出excel，我们的单元格不能为null值，否则报错。
        return "";
    }


    //大标题的样式
    public CellStyle bigTitle(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("宋体");
        font.setFontHeightInPoints((short)16);
        font.setBold(true);//字体加粗
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        return style;
    }

    //小标题的样式
    public CellStyle title(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("黑体");
        font.setFontHeightInPoints((short)12);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);				//横向居中
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线
        return style;
    }

    //文字样式
    public CellStyle text(Workbook wb){
        CellStyle style = wb.createCellStyle();
        Font font = wb.createFont();
        font.setFontName("Times New Roman");
        font.setFontHeightInPoints((short)10);

        style.setFont(font);

        style.setAlignment(HorizontalAlignment.LEFT);				//横向居左
        style.setVerticalAlignment(VerticalAlignment.CENTER);		//纵向居中
        style.setBorderTop(BorderStyle.THIN);						//上细线
        style.setBorderBottom(BorderStyle.THIN);					//下细线
        style.setBorderLeft(BorderStyle.THIN);						//左细线
        style.setBorderRight(BorderStyle.THIN);						//右细线

        return style;
    }
}
